package com.iretailer.report.web.system;

import com.iretailer.report.base.BaseAction;
import com.iretailer.report.dto.PageResult;
import com.iretailer.report.dto.QueryOption;
import com.iretailer.report.dto.ReQuartTask;
import com.iretailer.report.model.User;
import com.iretailer.report.quartz.QuartzService;
import com.iretailer.report.quartz.model.QuartTask;
import com.iretailer.report.util.RMap;
import com.iretailer.report.util.SecurityUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @Auther Bennie
 * @Date 2020/7/1 10:55
 * @Description
 */
@RestController
@Slf4j
public class QuatrzContoller extends BaseAction {

    @Autowired
    private QuartzService quartzService;

    @RequestMapping("/business/gridTask.action")
    public Map<String, Object> gridTask(@RequestBody ReQuartTask reQuartTask, HttpServletRequest request) {
        User user = SecurityUserUtil.currentUser(request);
        String companyId = user.getCompanyId();
        String roleId = user.getRoleId();
        if (roleId.equals("-")) {
            companyId = null;
        }
        QueryOption queryOption = modelMapper.map(reQuartTask, QueryOption.class);
        PageResult<QuartTask> find = quartTaskService.selectPage(companyId, reQuartTask.getJobGroup(), reQuartTask.getJobName(), queryOption);
        return RMap.ok(find);
    }

    @RequestMapping("/business/saveOrUpdateTask.action")
    @Transactional
    public Map<String, Object> saveOrUpdate(@RequestBody ReQuartTask reQuartTask) {
        boolean result = quartTaskService.saveOrUpdateTask(reQuartTask);
        return RMap.resultBoolean(result);
    }

    @RequestMapping("/business/deleteTask.action")
    public Map<String, Object> deleteTask(@RequestBody List<String> ids) {
        boolean result = quartTaskService.removeByIds(ids);
        if (result) {
            Collection<QuartTask> quartTasks = quartTaskService.listByIds(ids);
            for (QuartTask quartTask : quartTasks) {
                try {
                    quartzService.deleteJob(quartTask.getJobName(), quartTask.getJobGroup());
                } catch (SchedulerException e) {
                    log.error(e.getMessage(), e);
                    result = false;
                }
            }
        }
        return RMap.resultBoolean(result);
    }

}
